package com.example.baselib.activity

import android.content.Context
import android.graphics.Color
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import android.os.Build
import android.util.Log
import android.view.*
import android.view.View.*
import android.widget.LinearLayout
import androidx.annotation.LayoutRes
import androidx.annotation.Nullable
import androidx.appcompat.widget.PopupMenu
import androidx.core.view.isVisible
import com.alibaba.android.arouter.launcher.ARouter
import com.example.baselib.R
import com.example.baselib.constants.ARConstants
import kotlinx.android.synthetic.main.activity_base.*
import android.util.DisplayMetrics
import android.view.Display
import android.view.WindowManager
import android.annotation.TargetApi
import androidx.core.app.ComponentActivity.ExtraData
import androidx.core.content.ContextCompat.getSystemService
import android.icu.lang.UCharacter.GraphemeClusterBreak.T
import com.example.baselib.constants.MyConstants


/**
 * @author sxygsj.
 * @creat time 2020/4/8 15:53.
 * @description [封装公用activity]
 * @chang time 2020/4/8 15:53.
 * @chang describe ""
 */
abstract class BaseActivity : AppCompatActivity() {
    private lateinit var parentLinearLayout: LinearLayout
    protected val TAG = this.javaClass.simpleName  //获取TAG的activity名称
    private var toast: Toast? = null //封装Toast对象
    var context: Context? = null
    private var statusColor = Color.TRANSPARENT //状态栏颜色
    private lateinit var popupMenu: PopupMenu



    override fun onCreate(savedInstanceState: Bundle?) {
//        window.addFlags(WindowManager.LayoutParams.FLAG_SECURE)//禁止截屏
        super.onCreate(savedInstanceState)
        ARouter.getInstance().inject(this)
        initStatus()
        setLayoutView()
        base_toolbar.setPadding(0, getStatusBarHeight(this), 0, 0)
        initView()   //初始化控件
        initData()  //设置数据


    }


    /**
     * @Description: [设置是否显示toolbar]
     * @Param:     isShowToolbar 是否显示
     * @Return:
     */
    protected fun setShowToolbar(isShowToolbar: Boolean) {
        if (!isShowToolbar) base_toolbar.visibility = GONE else
            base_toolbar.visibility = VISIBLE
    }

    /**
     * titleMsg 标题内容
     */
    protected fun setToolbarMsg(titleMsg: String) {
        toolbar_title.text = titleMsg
    }

    /**
     * @Description: [设置颜色]
     * @Param:
     * @Return:
     */
    protected fun setToolbarColor(@Nullable bgColor: Int, @Nullable txtColor: Int) {
        base_toolbar.background = getDrawable(bgColor)
        toolbar_title.setTextColor(resources.getColor(txtColor))
    }

    /**
     * 设置返回按钮图标
     */
    protected fun setToolbarBlackRes(resId: Int) {
        toolbar_back.setImageResource(resId)
    }

    /**
     * 设置menu按钮图标
     */
    protected fun setToolbarMenuRes(resId: Int) {
        toolbar_menu.setImageResource(resId)
    }

    /**
     * @Description: [设置menu]
     * @Param:
     * @Return:
     */
    protected fun setToolbarMenu(showMenu: Boolean, @Nullable menuId: Int) {
        toolbar_menu.isVisible = showMenu
        if (menuId != -1) popupMenu.menu.findItem(menuId)?.isVisible = false
    }

    /**
     * @Description: [设置是否显示状态栏]
     * @Param:
     * @Return:
     */
    protected fun setShowStatus(showStatus: Boolean) {
        if (!showStatus) {
            window.setFlags(
                WindowManager.LayoutParams.FLAG_FULLSCREEN
                , WindowManager.LayoutParams.FLAG_FULLSCREEN
            )
        }else{
            window.clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN)
        }
    }

    /**
     * @Description: [状态栏颜色]
     * @Param:
     * @Return:
     */
    protected fun setStatusColor(statuscolor: Int) {
        statusColor = statuscolor
    }

    /**
     * @Description: [设置状态栏文字是否深色]
     * @Param:
     * @Return:
     */
    protected fun setStatusDark(statusDark: Boolean) {
        if (statusDark) {
            window.decorView.systemUiVisibility = SYSTEM_UI_FLAG_LIGHT_STATUS_BAR//黑色
        } else
            window.decorView.systemUiVisibility = SYSTEM_UI_FLAG_VISIBLE //白色
    }

    /**
     * @Description: [显示提示]
     * @Param: msg 提示信息
     * @Return:
     */
    protected fun showToast(msg: String) {
        if (null == toast) {
            toast = Toast.makeText(context, msg, Toast.LENGTH_SHORT)
        } else {
            toast?.setText(msg)
        }
        runOnUiThread { toast?.show() }

    }

    /**
     * @Description: [初始化状态栏]
     * @Param:
     * @Return:
     */
    private fun initStatus() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
            window.decorView.systemUiVisibility =
                SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or SYSTEM_UI_FLAG_LAYOUT_STABLE
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS or WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION)
            window.statusBarColor = statusColor
        }


    }
    //通过反射获取状态栏高度，默认25dp
    private fun getStatusBarHeight(context: Context): Int {
        var statusBarHeight = dip2px(context, 25F)
        try {
            val clazz = Class.forName("com.android.internal.R\$dimen")
            val `object` = clazz.newInstance()
            val height = Integer.parseInt(
                clazz.getField("status_bar_height")
                    .get(`object`).toString()
            )
            statusBarHeight = context.resources.getDimensionPixelSize(height)
        } catch (e: Exception) {
            e.printStackTrace()
        }

        return statusBarHeight
    }
    //根据手机的分辨率从 dp 的单位 转成为 px(像素)
    fun dip2px(context: Context, dpValue: Float): Int {
        val scale = context.resources.displayMetrics.density
        return (dpValue * scale + 0.5f).toInt()
    }


    //获取是否存在NavigationBar
    fun checkDeviceHasNavigationBar(context: Context): Boolean {
        var hasNavigationBar = false
        val rs = context.resources
        val id = rs.getIdentifier("config_showNavigationBar", "bool", "android")
        if (id > 0) {
            hasNavigationBar = rs.getBoolean(id)
        }
        try {
            val systemPropertiesClass = Class.forName("android.os.SystemProperties")
            val m = systemPropertiesClass.getMethod("get", String::class.java)
            val navBarOverride = m.invoke(systemPropertiesClass, "qemu.hw.mainkeys") as String
            if ("1" == navBarOverride) {
                hasNavigationBar = false
            } else if ("0" == navBarOverride) {
                hasNavigationBar = true

            }
        } catch (e: Exception) {
            Log.e("Exxxxxxxxxxx",e.message)
            e.printStackTrace()
        }

        return hasNavigationBar

    }
    /**
     * 横屏可通过 widthPixels - widthPixels2 > 0 来判断底部导航栏是否存在
     * @param windowManager
     * @return true表示有虚拟导航栏 false没有虚拟导航栏
     */
    @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
    fun isNavigationBarShow(windowManager: WindowManager): Boolean {
        val defaultDisplay = windowManager.defaultDisplay
        //获取屏幕高度
        val outMetrics = DisplayMetrics()
        defaultDisplay.getRealMetrics(outMetrics)
        val heightPixels = outMetrics.heightPixels
        //宽度
        val widthPixels = outMetrics.widthPixels


        //获取内容高度
        val outMetrics2 = DisplayMetrics()
        defaultDisplay.getMetrics(outMetrics2)
        val heightPixels2 = outMetrics2.heightPixels
        //宽度
        val widthPixels2 = outMetrics2.widthPixels

        return heightPixels - heightPixels2 > 0 || widthPixels - widthPixels2 > 0
    }
    /**
     * 获取底部导航栏高度
     * @param context
     * @return
     */
    fun getNavigationBarHeight(context: Context): Int {
        val resources = context.resources
        val resourceId = resources.getIdentifier("navigation_bar_height", "dimen", "android")
        val height = resources.getDimensionPixelSize(resourceId)
//        Log.v("dbw", "Navi height:$height")
        return height
    }


    private fun setLayoutView() {
        initContentView(R.layout.activity_base)
        setContentView(layoutResId())
    }


    /**
     * @Description: [封装toolbar标题栏]
     * @Param:
     * @Return:
     */
    private fun initContentView(@LayoutRes layoutResID: Int) {
        val viewGroup = findViewById<View>(android.R.id.content) as ViewGroup
        viewGroup.removeAllViews()
        parentLinearLayout = LinearLayout(this)
        parentLinearLayout.orientation = LinearLayout.VERTICAL
        viewGroup.addView(parentLinearLayout)
        //  add the layout of BaseActivity in parentLinearLayout
        LayoutInflater.from(this).inflate(layoutResID, parentLinearLayout, true)
        initMenu()
        toolbar_back.setOnClickListener { backOnClick() }
        toolbar_menu.setOnClickListener { popupMenu.show() }
    }


    /**
     * @Description: [可重写的回退事件]
     * @Param:
     * @Return:需要执行的回退方法
     */
    protected open fun backOnClick() {
        finish()
    }

    private fun initMenu() {
        popupMenu = PopupMenu(this, toolbar_menu)//1.实例化PopupMenu
        menuInflater.inflate(R.menu.menu, popupMenu.menu)//2.加载Menu资源
        popupMenu.setOnMenuItemClickListener(PopupMenu.OnMenuItemClickListener { item ->
            when (item.itemId) {
                R.id.menu_home -> {
                    finish()
                    true
                }
                R.id.menu_rydw -> {

                    if (MyConstants.userData.usertype==1){
                        ARouter.getInstance().build(ARConstants.APP_RYDW)
                            .navigation()
                    }else{
                        ARouter.getInstance().build(ARConstants.APP_RYDW_NICK)
                            .navigation()
                    }
                    finish()
                    true
                }
                R.id.menu_safe -> {
                    if (MyConstants.userData.usertype==1){
                        ARouter.getInstance().build(ARConstants.APP_SAFE)
                            .navigation()
                    }else{
                        ARouter.getInstance().build(ARConstants.APP_SAFE_NICK)
                            .navigation()
                    }
                    finish()
                    true
                }
                R.id.menu_video -> {
                    ARouter.getInstance().build(ARConstants.APP_VIDEO)
                        .navigation()
                    finish()
                    true
                }
                else -> false
            }
        })

    }


    override fun setContentView(layoutResID: Int) {
        val view=LayoutInflater.from(this).inflate(layoutResID, parentLinearLayout, true)
        if(isNavigationBarShow(windowManager)){
            view.setPadding(0, 0, 0, getNavigationBarHeight(this))
        }else {
            view.setPadding(0, 0, 0, 0)
        }
    }

    /**
     * @Description: [加载子布局]
     * @Param:
     * @Return:
     */
    protected abstract fun layoutResId(): Int

    /**
     * @Description: [初始化控件]
     * @Param:
     * @Return:
     */
    protected abstract fun initView()

    /**
     * @Description: [设置数据]
     * @Param:
     * @Return:
     */
    protected abstract fun initData()


    /**
     * 保证同一按钮在1秒内只会响应一次点击事件
     */
    //两次点击按钮之间的间隔，目前为1000ms
    private val MIN_CLICK_DELAY_TIME = 1000
    private var lastClickTime:Long = 0
    fun isFastClick():Boolean {
        var flag = true
        var currentClickTime = System.currentTimeMillis()
        if ((currentClickTime - lastClickTime) >= MIN_CLICK_DELAY_TIME ) {
            flag = false
        }
        lastClickTime = currentClickTime;
        return flag
    }


}
